Assignment almost finished aside from this little issue. Using poll because for some reason cygwin freezes without it. Parent process copies command line arguments to string and then sends it a character at a time to the child process, while counting, character by character and finally outputting the number of characters in the arguments.
I set i to 1 in loop control so that it ignores the first argument (the exe name of course).
It works fine as long as my first argument doesn't exceed 4 characters (any following arguments are counted just fine.) Any ideas?
Code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h> // for fork(), sleep()
#include <sys/wait.h> // for waitpid()
#include <sys/poll.h> // for poll()
static int stop = 0;
static char line[256];
static int comm[2];
int main (int argc, char **argv)
{
pid_t pid;
int status;
char ch;
int nChars;
// set up pipe
if (pipe(comm)) {
printf("pipe error\n");
return -1;
}
// fork into parent and child processes
pid = fork();
// fork() failed
if (pid < 0) {
printf("fork error %d\n", pid);
return -1;
}
else if (pid == 0) {
struct pollfd pollSpec;
close(comm[1]); // child doesn't need output side
// set up to poll input end of pipe
pollSpec.fd = comm[0];
pollSpec.events = POLLIN;
printf("child recieving: ");
while ( poll(&pollSpec, 1, 1000)){
read(comm[0], &ch, 1);
nChars++;
printf("%c", ch); //print characters as child recieves them
fflush(stdout); // override line buffering
sleep(1);// 1 second
}
printf("\nchild: counted %d characters\n", nChars);
close(comm[0]);
printf("child exits\n");
return 0;
}
//parent process
else {
close(comm[0]); //parent doesn't need input side
printf("parent waiting\n");
int i, j;
for(i = 1; i < argc; i++)
{
strcpy(line, argv[i]); //copy command line arguments to array
for(j = 0; j < sizeof(argv[i]); j++)
{
ch = line[j];
if(ch != '\0'){
write(comm[1], &ch, 1); //send characters to child
sleep(1);
}
}
}
stop = 1; // tell child to stop via global variable
printf("parent tells child to stop\n");
waitpid(pid, &status, 0);
printf("parent reaps child status 0x%08X\n", status);
if (WIFEXITED(status))
printf("child exited normally with %d\n", WEXITSTATUS(status));
close(comm[1]);
printf("parent exits\n");
return 0;
}
}